<?php
class Login extends CI_Controller{
	function __construct(){
		parent::__construct();
		$this->load->library('form_validation');	
	}
	
	function index(){
		if ($this->session->userdata('logged_in')){
			redirect('/site');
		}
		$this->load->view('loginForm');		
	}
	
	function processLogin(){
		$config= array(
			array(
				'field' => 'username',
				'label' => 'Username',
				'rules' => 'required|trim|callback_authenticate'
			),
			array(
				'field' => 'password',
				'label' => 'Password',
				'rules' => 'trim|required'
			)
		);
		$this->form_validation->set_rules($config);
		$this->form_validation->set_message('authenticate','Invalid Login. Please try again.');
		
		if ($this->form_validation->run()){
			$username = $this->input->post('username');
			$user = $this->usermodel->getUser($username);
			foreach ($user as $r){
				$userType = $r -> type;
				$userId = $r -> user_id;
				$fname = $r->firstname;
				$lname = $r->lastname;
			}
			$data = array(
				'username' => $username,
				'logged_in' => true,
				'user_type' => $userType,
				'user_id' => $userId,
				'name' => $fname.' '.$lname
			);
			$this->session->set_userdata($data);
			$this->load->model('liststudent');
			$status = $this->liststudent->checkStatus($userId);
			$content['title'] = 'List';
			$studentId = $this->session->userdata('user_id');
			$this->load->model('thesismodel');
			$content['rows'] = $this->thesismodel->registeredTopic($studentId);
			$this->session->set_userdata('status',$status);
			if ($userType == 1 && $status == 2 || $status == 3){
				$this->load->view('student/registeredTopic',$content);
			}
			else
				redirect('/site');
		}
		else
			$this->load->view('loginForm');;
	}
	
	function authenticate(){
		$this->load->model('usermodel');
		$query = $this->usermodel->validate();
		
		return $query;
	}
	
	function logout(){
		$this->session->sess_destroy();
		redirect('/login');
	}
}
?>